home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 5207 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.2 KB  |  73 lines

  1. Path: EU.net!sun4nl!ittpub!ittpub!nntp
  2. Newsgroups: comp.lang.c++
  3. Subject: Re: g++ warning about initialization of non-const obj& - help needed
  4. Message-ID: <1996Feb2.152455.1767@ittpub>
  5. From: wil@ittpub.nl (Wil Evers)
  6. Date: 2 Feb 96 15:24:54 WET
  7. References: <4eo63u$kr1@llnews.ll.mit.edu>
  8. Distribution: world
  9. Nntp-Posting-Host: lintilla
  10.  
  11. In article <4eo63u$kr1@llnews.ll.mit.edu> kappu@ll.mit.edu (Kalpana  
  12. Subramanian) writes:
  13.  
  14. > Hello g++ users,
  15. > I have a function declared as such:
  16. >     func( obj &)
  17. > I go to use it thus:
  18. >     func( obj.memberfunc() returning an obj);
  19. > I get a warning -
  20. >     warning: initialization of non-const `obj &' from rvalue `obj'
  21. > If I make a temporary obj, obj2 = obj.memberfunc()returning an obj,
  22. > and call func(obj2), it compiles.
  23. > In reading the FAQ, I understand that temporaries inside function calls
  24. > that require conversion can get deleted before the conversion process,
  25. > thus causing erroneous results and should be avoided. However, in this
  26. > usage, the compiler should be able to make a reference from an object,
  27. > shouldn't it?  Is it that the compiler will only want to make a const
  28. > reference from an object? The code I am compiling was all compiled under 
  29. > previous versions of g++, and I wanted to upgrade it all. I am using 
  30. > gcc/g++2.7.2 on a SunOS 4.1.4 platform.
  31. > If this is obvious to anybody, could you please explain what the
  32. > issue is?
  33.  
  34. The problem here is in func()'s prototype. func() takes a reference to a  
  35. non-const obj, which is another way of saying that func() will probably  
  36. modify the object passed to it - and may have been defined to do just  
  37. that. However, since the modification will be done to a temporary that  
  38. will subsequently cease to exist, func()'s modifications will be lost -  
  39. and this could cause surprises.
  40.  
  41. To give a simple example, supposing we have
  42.  
  43. void inc(double& d)
  44. {
  45.     d += 1.0;
  46. }
  47.  
  48. and someone writes:
  49.  
  50. main()
  51. {
  52.     double d = 0.0;
  53.     float f = 0.0;
  54.     inc(d);
  55.     inc(f);
  56. }
  57.  
  58. Then the first call `inc(d)' *will* increment d, while to second call  
  59. `inc(f)' *won't* increment f. Instead, a temporary double is created,  
  60. which is then incremented and forgotten about. This is why the compiler  
  61. warns about these things.
  62.  
  63. - Wil
  64.